package com.jhw.ymcc.mq.consumer;

import com.jhw.ymcc.domain.CourseOrder;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.service.ICourseOrderService;
import com.jhw.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "course-order-handler-delay-group",
        topic = "course-order-handler-delay-topic",
        selectorExpression = "course-order-handler-delay-tag",
        messageModel = MessageModel.BROADCASTING
)
public class CourseOrderHandlerDelayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 消费者有一个签收模式：
     *  什么都不返回：签收成功
     *  报错了：签收失败，重新发送
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.业务校验
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotEmpty(orderNo, GlobalErrorCode.ERROR);

        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);
        if (courseOrder == null){
            return;
        }
        courseOrder.setUpdateTime(new Date());
        courseOrder.setStatusOrder(CourseOrder.CANCEL_PAY_STATUS);
        courseOrderService.updateById(courseOrder);
    }
}